package com.wandian.mvc
{
	import flash.display.Sprite;

	/**
	 *
	 * @memo 中介者模式
	 */
	public class Mediator
	{

		/**
		 *
		 * @default 所有的动作事件集合
		 */
		private var _interests:Array=[]
		//protected var base:Sprite
		/**
		 *
		 * @default 中介者名称
		 */
		private var _name:String
		/**
		 *
		 * @default 观察者
		 */
		internal var facade:Facade

		/**
		 *
		 * @param name 中介者名称
		 * @param ui 指派显示的帧
		 */
		public function Mediator(name:String, ui:Sprite)
		{
			this._name=name
		}

		/**
		 *
		 * @param type
		 * @param body
		 */
		protected function dispatchAction(type:String, body:Object):void
		{
			if (facade != null)
			{
				facade.dispatchAction(this, type, body)
			}
		}

		/**
		 *
		 * @param type
		 * @param body
		 * @return
		 */
		protected function dispatchActionForResult(type:String, body:Object):Object
		{
			var result:Object=null
			if (facade != null)
			{
				result=facade.dispatchActionForResult(this, type, body)
			}
			return result;
		}

		/**
		 * 由继承者去实现，具体的事件，switch语句
		 * @param action
		 */
		internal function ActionHandler(action:Action):void
		{
			trace("MVC : " + this + " <<< " + action.type);
			handleAction(action)
		}

		/**
		 *
		 * @param action
		 */
		protected function handleAction(action:Action):void
		{

		}

		/**
		 * 根据事件名遍历数组，返回索引
		 * @param type
		 * @return
		 */
		private function getInterestIndex(type:String):int
		{
			for (var i:int=0; i < _interests.length; i++)
			{
				if (_interests[i] == type)
				{
					return i
				}
			}
			return -1;
		}

		/**
		 * 增加一个事件
		 * @param type 事件名称
		 */
		protected function addInterest(type:String):void
		{
			if (getInterestIndex(type) > -1)
			{
				return;
			}
			_interests.push(type)
			if (facade != null)
			{
				facade.addListener(type, this.handleAction);
			}
		}

		/**
		 * 移除事件
		 * @param type
		 */
		protected function removeInterest(type:String):void
		{
			var p:int=getInterestIndex(type);
			if (p == -1)
			{
				return;
			}
			_interests.splice(p, 1);
			if (facade != null)
			{
				facade.removeListener(type, this.handleAction);
			}

		}

		/**
		 * 返回中介者的名称
		 * @return
		 */
		public function get name():String
		{
			return this._name
		}

		/**
		 *
		 * @return 返回所有的事件
		 */
		public function get interests():Array
		{
			return _interests;
		}

	}
}
